/**
 * Created by Jackie on 2016/11/10.
 */

if (typeof Poly9 == 'undefined') {
    var Poly9 = {};
}

/**
 * Creates an URLParser instance
 *
 * @classDescription    Creates an URLParser instance
 * @return {Object}    return an URLParser object
 * @param {String} url    The url to parse
 * @constructor
 * @exception {String}  Throws an exception if the specified url is invalid
 */
Poly9.URLParser = function (url) {
    var _this = this;

    this._fields = {
        'Username': 4,
        'Password': 5,
        'Port': 7,
        'Protocol': 2,
        'Host': 6,
        'Pathname': 8,
        'URL': 0,
        'Querystring': 9,
        'Fragment': 10
    };

    this._values = {};
    this._regex = null;
    this.version = 1;
    this._regex = /^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/;
    this._paramValues = {};
    this.lottering=false;
    var paramParsed = false;

    for (var f in this._fields) {
        this['get' + f] = this._makeGetter(f);
    }

    if (typeof url != 'undefined') {
        this._parse(url);
    }

    var parseQueryString = function (hash) {
        if (paramParsed) return _this._paramValues;
        if (hash == null || hash.length <= 0) return null;
        var items = hash.split("&"), i, item;
        for (i = 0, j = items.length; i < j; i++) {
            item = items[i].split("=");
            if (item.length === 2 && item[0].length > 0) {
                _this._paramValues[item[0]] = decodeURIComponent(item[1]);
            }
        }
        paramParsed = true;
        return _this._paramValues;
    };

    this.getQuery = function (key) {
        var param = parseQueryString(_this.getQuerystring());
        if (param == null) return null;
        return param[key];
    }
}

/**
 * @method
 * @param {String} url    The url to parse
 * @exception {String}     Throws an exception if the specified url is invalid
 */
Poly9.URLParser.prototype.setURL = function (url) {
    this._parse(url);
}

Poly9.URLParser.prototype._initValues = function () {
    for (var f in this._fields) {
        this._values[f] = '';
    }
}

Poly9.URLParser.prototype._parse = function (url) {
    this._initValues();
    var r = this._regex.exec(url);
    if (!r) throw "DPURLParser::_parse -> Invalid URL";

    for (var f in this._fields) if (typeof r[this._fields[f]] != 'undefined') {
        this._values[f] = r[this._fields[f]];
    }
}

Poly9.URLParser.prototype._makeGetter = function (field) {
    return function () {
        return this._values[field];
    }
}

function Model() {
    var self = this
    this.mask = $('.wt_mask')
    this.confirm = $('.wt_confirm')
    this.inputs = {
        name: $('.name'),
        phone: $('.phone'),
        account: $('.account')
    }
    this.content = $('.wt_confirm_ctn_inner')
    this.alertContent = $('.wt_confirm_ctn_inner_alert')
    this.pointSuccessContent = $('.points_success')
    this.btns = $('.wt_confirm_btns')
    this.btn_close = $('.wt_close')

    $('.j-ok').bind('touchstart', function () {
        self.okcall && self.okcall()
        self.close()
    })
    $('.j-cancel').bind('touchstart', function () {
        self.close()
    })
}

$.extend(Model.prototype, {
    open: function (type, text, okcall, closeall) {
        var self = this
        this.mask.show()
        this.confirm.show()
        this.btn_close.show()

        this.okcall = okcall
        this.closeall = closeall
        if (type == 'alert') {
            this.mask.hide()
            this.alertContent.show()
            this.alertContent.html(text)
            this.btns.hide()
            this.content.hide()
            this.btn_close.hide()

            this.timer = setTimeout(function () {
                self.close()
            }, 3000)

        } else if (type == 'exchange') {
            this.pointSuccessContent.show()
            this.btns.hide()
            this.alertContent.hide()
            this.content.hide()
        } else if (type == 'confirm') {
            this.btns.show()
            this.content.html(text)
            this.content.show()
            this.alertContent.hide()
        } else {
            this.btns.hide()
            this.content.html(text)
            this.content.show()
            this.alertContent.hide()
        }
    },
    close: function () {
        clearTimeout(this.timer)
        this.mask.hide()
        this.confirm.hide()
        this.pointSuccessContent.hide()
        isPrizeing = false
        if (this.closeall) this.closeall()
    },
    getValue: function (name) {
        return this.inputs[name].val()
    },
    clear: function () {
        this.input.val('')
    }

})

function Activity() {

}

var HOST = location.origin
// var HOST = 'http://119.29.169.29'


$.extend(Activity.prototype, {
    transferDateStr2Obj: function (date) {
        if (typeof date === 'string') {
            date = new Date(date.replace(/-/g, '/'))
        }

        if (typeof date === 'number') {
            date = new Date(date)
        }

        return date
    },
    taskCountDown: function (item) {

        var now = new Date
        var endDate = this.transferDateStr2Obj(item.end_time)
        var rest = (endDate - now) / 1000

        item.classname = '.JCountDown_' + item.id

        item.$dom = $(item.classname)

        if (rest < 0) {
            item.text = '任务已结束'
            item.$dom.text(item.text)
            return
        }

        item.timer = setInterval(function () {
            rest = rest - 1
            if (rest <= 0) {
                clearInterval(item.rest)
                return
            }
            item.text = this.transSecond2Text(rest)
            item.$dom.text(item.text)
        }.bind(this), 1000)

    },

    transSecond2Text: function (second_time) {
        var time = parseInt(second_time) + "秒";
        if (parseInt(second_time) > 60) {
            var second = parseInt(second_time) % 60;
            var min = parseInt(second_time / 60);
            time = min + "分" + second + "秒";
            if (min > 60) {
                min = parseInt(second_time / 60) % 60;
                var hour = parseInt(parseInt(second_time / 60) / 60);
                time = hour + "小时" + min + "分" + second + "秒";
                if (hour > 24) {
                    hour = parseInt(parseInt(second_time / 60) / 60) % 24;
                    var day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
                    time = day + "天" + hour + "小时" + min + "分" + second + "秒";
                }
            }
        }
        return time;
    },
    saveStorage: function (obj) {
        var storage = localStorage
        storage.setItem("saveJson", JSON.stringify(obj));
    },
    init: function (key) {
        var self = this
        var json = localStorage.getItem("saveJson");
        self.params = null
        self.timer = null
        self.countdown = 60
        self.page = 1 //页码

        if (json != null)
            self.params = JSON.parse(json);

        self.model = new Model()
        self.bindEvents()

        if (key) {
            self[key](self)
        }

        this.addScore()
    },
    addScore: function () {

        var parser = new Poly9.URLParser(location.href)
        var data = {
            user_id: parser.getQuery('user_id'),
            act_id: parser.getQuery('act_id')
        }
        if (data.user_id && data.act_id) {
            if (data.user_id != localStorage.user_id)
                this.doAddScore(data)
        }
    },
    renderTasks: function (self) {
        var isPageHide = false
        window.addEventListener('pageshow', function () {
            if (isPageHide) {
                window.location.reload()
            }
        })
        window.addEventListener('pagehide', function () {
            isPageHide = true
        })

        self.services.tasks({
            phone: localStorage.phone,
            version: Date.now()
        }, function (res) {

            var tpl = $('.tpl').html()
            var html = _.template(tpl)({list: res.err_msg.list})
            $('.JList').append(html)

            localStorage.tasks = JSON.stringify(res.err_msg.list)

            res.err_msg.list.forEach(function (item) {

                self.taskCountDown(item)
            })

        })

    },
    renderTaskDetail: function (self) {
        var parser = new Poly9.URLParser(location.href)
        var id = parser.getQuery('id')
        var tasks = JSON.parse(localStorage.tasks)

        var task = tasks.filter(function (item) {
            return item.id == id
        })

        if (task && task.length > 0) {
            task = task[0]

            $('.Jtitle').text(task.title)
            $('.Jdescription').html(task.description)
        }

        var clientHeight = document.documentElement.clientHeight

        $('.banner').height()

        var h = clientHeight - $('.banner').height() - 10
        $('.wrap').height(h)

        if (task.status == 1) {
            self.services.taskEnter({
                phone: localStorage.phone,
                id: id
            }, function (res) {
                self.model.open('alert', res.err_msg)
            })
        }

    },
    renderAccount: function (self) {
        var storage = localStorage
        $('input[name=name]').val(storage['name']);
        $('input[name=account]').val(storage['account']);
        $('input[name=phone]').val(storage['phone']);
        $('input[name=address]').val(storage['address']);
    },
    renderSigninDetail:function(self){
        this.services.loadConfig(
            function (data) {
                data=data.err_msg;
                for(var i=0;i<data.length;i++){
                    if(data[i]["key"]=="sign"){
                        $('.detail').html(data[i]['value']);
                        break;
                    }
                }
        })
    },
    renderDetail: function (self) {
        this.services.activityIndex({
            type: 1,
            order: 'desc',
            phone: localStorage.phone
        }, function (res) {
            if (res.err_code == 200) {
                $('.JShare').attr('id', res.err_msg.id)
                $('.JExchangeEnroll').attr('id', res.err_msg.id)
                $('.JContent').html(res.err_msg.description)
            }
        })
    },
    renderRecord: function (self) {
        this.services.lotteryRecord({
            phone: localStorage.phone
        }, function (res) {
            var tpl = $('.tpl').html()
            var html = _.template(tpl)({list: res.err_msg.data})
            if (self.page == 1) {
                $('.JList').html('')
            }
            $('.JList').append(html)
            if (res.err_msg.page.total_pages > this.page) {
                $('.JMore').show()
            } else {
                $('.JMore').hide()
            }
        })
    },
    renderWheel: function (self) {
        localStorage.lottery_time = Number(localStorage.lottery_time) >= 0 ? localStorage.lottery_time : 0
        $('.lottery_time').text(localStorage.lottery_time)
        $('.JScore').text(localStorage.score)
        self.services.lotteryIndex({
            phone: localStorage.phone
        }, function (res) {
            if (res.err_code == '200') {
                self.lotteryScore = res.score
            } else {
                self.err_msg = res.err_msg
                self.model.open('alert', res.err_msg)
            }

            drawRouletteWheel([
                {"id": "1", "name": "谢谢参与"},
                {
                    "id": "2",
                    "name": "10元嘀嘀打车券 "
                }, {"id": "3", "name": "免费话费"},
                {
                    "id": "4",
                    "name": "移动流量"
                },
                {"id": "5", "name": "10元京东E卡"},
                {
                    "id": "6",
                    "name": "中石化加油卡"
                },
                {"id": "7", "name": "iwatch 2"},
                {"id": "8", "name": "iPhone"}])
        })
    },
    renderScoreHis: function (self) {
        this.page = self.page

        $('.JScore').text(localStorage.score)
        this.services.exchangeDetail({
            phone: localStorage.phone,
            page: this.page
        }, function (res) {
            if (res.err_code == 200) {
                var tpl = $('.tpl').html()
                var html = _.template(tpl)({list: res.err_msg.data})
                if (self.page == 1) {
                    $('.JList').html('')
                }
                $('.JList').append(html)
                if (res.err_msg.page.total_pages > this.page) {
                    $('.JMore').show()
                } else {
                    $('.JMore').hide()
                }
            }
        })

        if (this.page == 1) {
            $('.JMore').bind('click', function () {
                self.page = self.page + 1
                self.renderPoints(self)
            })
        }
    },
    renderExchange: function (self) {
        this.page = self.page

        $('.JScore').text(localStorage.score)
        this.services.exchangeRecord({
            phone: localStorage.phone,
            page: this.page
        }, function (res) {
            if (res.err_code == 200) {
                var tpl = $('.tpl').html()
                var html = _.template(tpl)({list: res.err_msg.data})
                if (self.page == 1) {
                    $('.JList').html('')
                }
                $('.JList').append(html)
                if (res.err_msg.page.total_pages > this.page) {
                    $('.JMore').show()
                } else {
                    $('.JMore').hide()
                }
            }
        })
        if (this.page == 1) {
            $('.JMore').bind('click', function () {
                self.page = self.page + 1
                self.renderExchange(self)
            })
        }

    },
    /* 新手福利 */
    renderNewfish: function () {
        var self = this
        this.services.BeginnerWelfare({phone: localStorage.phone}, function (res) {
            if (res.err_code == 200) {
                if (res.err_msg && res.err_msg.list && res.err_msg.list.length > 0) {
                    var list = res.err_msg.list

                    var tpl = $('.tpl').html()
                    var html = _.template(tpl)({list: list})
                    $('.JList').html(html)
                }
            } else {
                self.model.open('alert', res.err_msg)
            }
        })
    },
    doPointsTypeChange: function (type) {
        var params = {
            order: this.order || 'desc',
            type: type
        }

        this.renderPoints(this, params)
    },
    doSort: function () {

        this.order = this.order == 'asc' ? 'desc' : 'asc'
        var type = $('.JPointsType').val()
        var params = {
            order: this.order,
            phone: localStorage.phone
        }

        if (type) {
            params.type = type
        }

        this.renderPoints(this, params)
    },
    renderPoints: function (self, params) {

        $('.JScore').text(localStorage.score)

        params = params || {}

        params.phone = localStorage.phone
        this.services.exchangeIndex(params, function (res) {
            if (res.err_code == 200) {
                var tpl = $('.tpl').html()
                var html = _.template(tpl)({list: res.err_msg.list})
                $('.JList').html(html)
                $('.JRed').html(res.err_msg.page.total)
            }
        })
    },
    renderUserCenter: function () {

        $('.Jfooter').show()
        $('.Jname').text(localStorage.name)


            setTimeout(function () {
                this.services.special({phone: localStorage.phone}, function (res) {
                    if (res.err_code == 200) {
                        var tpl = $('.tpl-gift').html()
                        var html = _.template(tpl)({list: res.err_msg.list})
                        $('.JGiftList').html(html)
                        if (sessionStorage['dialog-gift_hide'] == null) {
                            sessionStorage['dialog-gift_hide'] = 0;

                            if(res.err_msg.list.length>0){
                                $('.dialog-gift').fadeIn(350)
                                $('.JShownGiftDialog').show();
                            }
                            else{
                                $('.JShownGiftDialog').hide();
                            }

                        }
                    }
                })

            }.bind(this), 1000)


        this.services.userCenter({}, function (res) {
            if (res.err_code == 10000) {
                myAct.doGoHref('login.html');
            } else {
                for (var i in res.err_msg) {
                    localStorage[i] = res.err_msg[i]
                }
                $('.JLottery_time').text(res.err_msg.lottery_time)

                // $('.JBanner').attr('src', res.data.url)
            }
        })

        var loginData = JSON.parse(localStorage.loginData)

        if (loginData.isShowBenginnerWelfare) {

            this.services.BeginnerWelfare({phone: localStorage.phone}, function (res) {
                if (res.err_code == 200) {
                    if (res.err_msg && res.err_msg.list && res.err_msg.list.length > 0) {
                        var data = res.err_msg.list[0]
                        data && data.name && $('.JNewfishTop1').text(data.name)
                        $('.JNewfishBox').show()
                    }
                } else {
                    self.model.open('alert', res.err_msg)
                }
            })
        }
    },
    renderTimelimit: function () {
        var self = this

        this.services.special({phone: localStorage.phone}, function (res) {
            if (res.err_code == 200) {
                var tpl = $('.tpl').html()
                var html = _.template(tpl)({list: res.err_msg.list})
                $('.JList').html(html)

            }
        })
    },
    sub: function (e, t) {
        return e.replace(/\${(.*?)}/gim, function (e, a) {
            return "string" == typeof t ? t : "undefined" == typeof t[a] ? "" : t[a]
        })
    },

    doLogin: function (params) {
        var self = this,
            referList = ['points.html']
        var phone

        params.forEach(function (item) {
            if (item.name == 'phone') {
                phone = item.value
            }
        })
        self.services.login(params, function (res) {
            $("input").blur()
            if (res.err_code == 200) {
                localStorage.user_id = res.data.userId
                localStorage.phone = phone
                localStorage.loginData = JSON.stringify(res.data)
                var page = document.referrer.substr(document.referrer.lastIndexOf('/'))
                self.model.open('alert','“乐享周日 靠浦福利”活动系统维护通知<br /><br />尊敬的用户，您好！感谢您在2017年对“乐享周日 靠浦福利”活动的支持，在元旦来临之际，为了给您提供更优质的活动体验，“乐享周日 靠浦福利”活动平台将于2018年1月1日凌晨起进行系统维护，维护时间预计需要24小时。');
                setTimeout(function () {
                    if (document.referrer && referList.indexOf(page) > -1) {
                        myAct.doGoHref(document.referrer)
                    } else {
                        myAct.doGoHref('detail.html')
                    }
            },3000);
        } else {
            self.model.open('alert', res.err_msg)
        }
    })

    },
    doRest: function (params) {
        var self = this

        self.services.reset(params, function (res) {
            $("input").blur()
            if (res.err_code == 200) {
                self.model.open('alert', '成功')
                setTimeout(function () {
                    myAct.doGoHref('login.html')
                }, 1000);
            } else {
                self.model.open('alert', res.err_msg)
            }
        })
    },
    doChange: function (params) {
        var self = this

        self.services.change(params, function (res) {
            $("input").blur()
            if (res.err_code == 200) {
                self.model.open('alert', '成功')
                setTimeout(function () {
                    myAct.doGoHref('login.html')
                }, 1000);
            } else {
                self.model.open('alert', res.err_msg)
            }
        })
    },
    doRegister: function (params) {
        var self = this

        var phone

        params.forEach(function (item) {
            if (item.name == 'phone') {
                phone = item.value
            }
        })

        self.services.register(params, function (res) {
            $("input").blur()
            if (res.err_code == 200) {

                localStorage.user_id = res.data
                localStorage.phone = phone

                self.model.open('alert', '注册成功')
                myAct.doGoHref('index.html');
                /**location.href = 'http://activity.m.yiguo.com/201704251.html?dm=bcspdb.yiguo.com'**/

            } else {
                self.model.open('alert', res.err_msg)
            }
        })

    },
    setcountdown: function () {
        var self = this
        $('.JCount').show()

        self.timer && clearInterval(self.timer)

        $('.JGetCode')[0].disabled = true
        self.timer = setInterval(function () {

            if (self.countdown == 0) {
                self.countdown = 60
                clearInterval(self.timer)
                $('.JCount').hide()
                $('.JGetCode')[0].disabled = false

            } else {
                self.countdown = self.countdown - 1
            }
            $('.Jnum').text(self.countdown)

        }, 1000)

    },
    doExchange: function (id, score) {
        var self = this
        this.services.exchange({
            phone: localStorage.phone,
            prize: id
        }, function (res) {

            if (res.err_code == 200) {

                $('.dialog-gift').hide()

                localStorage.score = localStorage.score - score
                $('.JScore').text(localStorage.score)
                self.model.open('exchange', res.err_msg)
            } else {
                self.model.open('alert', res.err_msg)

            }
        })
    },
    doExchangeEnroll: function (params) {
        this.services.exchangeEnroll(params, function (res) {
            // self.model.open('alert', res.err_msg)
            if (res.err_code != 10002)
                alert(res.err_msg)
            myAct.doGoHref('index.html');
        })
    },
    doAddScore: function (params) {
        this.services.activityAddScore(params, function (res) {
        })
    },
    doShare: function (act_id) {
        var url = this.services.HOST + '/new/login.html?user_id=' + localStorage.user_id + '&act_id=' + act_id
        var html = '<p>分享给微信好友或者QQ好友，</p><p>请复制链接： </p><textarea class="textarea" readonly="readonly">' + url + '</textarea>'
        this.model.open('share', html, true)
    },
    doGoHref: function (href, params) {

        var parser = new Poly9.URLParser(location.href)

        var user_id = localStorage.user_id
        var act_id = parser.getQuery('act_id')
        var result = []

        if (!act_id) {
            act_id = "1"
        }

        params = $.extend({user_id: user_id, act_id: act_id}, params)

        for (var key in params) {
            result.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]))
        }

        result = result.join('&')
        result = '?' + result

        location.href = href + result
    },
    doLottery: function (self) {
        self.lottering=true;
        self.services.lottery({
            phone: localStorage.phone
        }, function (res) {
            self.lottering=false;
            if (res.err_code == 200) {
                if (turnplate.bRotate)return;
                turnplate.bRotate = !turnplate.bRotate;

                rotateFn(res.err_msg.id * 1, turnplate.restaraunts[res.err_msg.id - 1], function () {
                    self.model.open('alert', res.err_msg.name)
                })

                localStorage.lottery_time = res.user.lottery_time
                localStorage.score = res.user.score

                $('.lottery_time').text(localStorage.lottery_time)
                $('.JScore').text(localStorage.score)

            } else {
                self.model.open('alert', res.err_msg)
            }
        })
    },
    doSignIn: function (self) {

        self.services.signIn({phone: localStorage.phone}, function (res) {
            $('.JSignDialog').fadeIn(350)
            if (res.err_code == 200) {
                if (res.err_msg.signDays == 7) {
                    $('.Jsuccess2').show()
                }
                else {
                    $('.Jsuccess1').show()
                    $('.JsignDays').text(res.err_msg.signDays)
                }
            } else {
                $('.Jfail').show()
                $('.JfailResult').text(res.err_msg);
            }
        })
    },
    doUpdateUser: function (data) {
        var self = this
        this.services.updateUserCenter(data, function (res) {
            self.model.open('alert', res.err_msg)

            if (res.err_code == 200) {

                data.forEach(function (item) {

                    if (item.name != 'code') {

                        localStorage[item.name] = item.value
                        $('p.' + item.name).text(item.value)
                    }

                })
                history.back();
            }

        })
    },
    bindEvents: function () {
        var self = this

        $(document).on('tap', '.JShownGiftDialog', function () {
            $('.dialog-gift').fadeIn(500)
        })
        $(document).on('tap', '.JGoTaskDetail', function () {
            self.doGoHref('task-detail.html', {id: this.id})
        })

        $('.JUpdateUserInfo').on('tap', function () {
            var data = $('#formAccount').serializeArray()
            if(data.account==null || data.account.length<1){
                self.model.open('alert', '请输入卡号');
                return;
            }
            if(data.name==null || data.name.length<1){
                self.model.open('alert', '请输入姓名');
                return;
            }
            if(data.address==null || data.address.length<1){
                self.model.open('alert', '请输入地址');
                return;
            }
            self.doUpdateUser(data)
            return false;
        })

        $('.JSignDialogClose').on('tap', function () {

            $('.dialog-sign').fadeOut(350, function () {
                $('.Jfail').hide()
                $('.Jsuccess1').hide()
                $('.Jsuccess2').hide()
            })
            return false;
        })

        $('.JGiftDialogClose').on('tap', function () {
            $('.dialog-gift').fadeOut(350)
            return false;
        })

        //关model
        $(document).on('touchstart', '.j-close', function () {
            self.model.close()
        })

        $(document).on('change', '.JPointsType', function (evt) {
            var type = this.value
            self.doPointsTypeChange(type)
        })
        $(document).on('touchstart', '.JSort', function () {
            self.doSort()
        })
        //
        $(document).on('touchstart', '.pointer', function () {
            if(self.lottering)return;

            if (self.lotteryScore) {
                // if (confirm('本次抽奖需要消耗1次机会或扣除' + self.lotteryScore + '积分')) {
                //     self.doLottery(self)
                // }

                self.model.open('confirm', '本次抽奖需要消耗1次机会或扣除' + self.lotteryScore + '积分', function () {
                    self.doLottery(self)

                })

            } else {
                self.model.open('alert', self.err_msg)
            }

        })

        $(document).on('touchstart', '.JExchange', function () {
            var _this = this
            var myScore = localStorage.score
            var score = _this.dataset.score

            // self.model.open('exchange', 11)
            // return

            if($(_this).attr('material')=='1' &&  (myScore['address']==null || myScore['address'].length<1)){
                alert('兑换前需要填写好寄送地址。')
                myAct.doGoHref('account.html')
                return;
            }

            if (Number(myScore) < Number(score)) {
                self.model.open('alert', '积分不足，无法兑换')

                return
            }



            self.model.open('confirm', '确认兑换该礼品？', function () {
                var id = _this.id
                var score = _this.dataset.score
                self.doExchange(id, score)
            })

        })
        $(document).on('touchstart', '.JExchangeEnroll', function () {

            var params = {
                id: this.id,
                phone: localStorage.phone
            }

            self.doExchangeEnroll(params)
        })
        $(document).on('touchstart', '.JRegister', function () {

            var data = $('.formRegister').serializeArray()

            self.doRegister(data)
        })
        $(document).on('touchstart', '.JLogin', function () {

            var data = $('.formLogin').serializeArray()

            self.doLogin(data)
        })

        $(document).on('touchstart', '.JRest', function () {

            var data = $('.formRest').serializeArray()
            self.doRest(data)
        })

        $(document).on('touchstart', '.JChange', function () {

            var data = $('.formChange').serializeArray()
            self.doChange(data)
        })
        $(document).on('touchstart', '.JShare', function () {

            var act_id = this.id
            self.doShare(act_id)
        })

        $('.JSignIn').on('tap', function () {
            self.doSignIn(self)
        })

        $(document).on('touchstart', '.JGetCode', function () {
            var formClass = $(this).attr('form')
            var form = $('.' + formClass)
            var data = form.serializeArray()

            if ($(this)[0].disabled) {
                return
            }

            self.services.code(data, function (res) {
                if (res.err_code == '200') {

                    self.setcountdown()

                } else {
                    self.model.open('alert', res.err_msg)
                }
            })
        })
    },
    // 新的抽奖页面
    renderNewprizes: function (self) {
        localStorage.lottery_time = Number(localStorage.lottery_time) >= 0 ? localStorage.lottery_time : 0
        $('.lottery_time').text(localStorage.lottery_time)
        self.getIndexVal(self)
        
    },
    getIndexVal: function (self) {
        self.services.lotteryIndex({
            phone: localStorage.phone
        }, function (res) {
            if (res.err_code == '200') {
                self.lotteryScore = res.score
                // 积分
                $('.JScore').text(localStorage.score)
                var tpl = $('.tpl').html()

                res.err_msg.push(res.err_msg[0])

                var html = _.template(tpl)({list: res.err_msg})

                $('.con ul').append(html)

                prizes.init($('.con ul'),'.button_container',function(){

                    if (self.lotteryScore >= self.lotteryScore || localStorage.lottery_time>0) {
                        self.model.open('confirm', '本次抽奖需要消耗1次机会或扣除' + self.lotteryScore + '积分', function () {
                            prizes.start();
                            setTimeout(function(){
                                self.getPostPrizes(self)
                            },2000);
                        })
                    } else {
                        self.model.open('alert','暂不能进行抽奖')
                    }

                },function(msg){
                    //调用成功
                    self.model.open('alert',msg)

                });
            } else {
                self.err_msg = res.err_msg
                self.model.open('alert', res.err_msg)
            }
        })
    },

    getPostPrizes: function (self) {
        self.services.lottery({
            phone: localStorage.phone
        }, function (res) {
            if (res.err_code == 200) {
                localStorage.lottery_time = res.user.lottery_time
                localStorage.score = res.user.score
                $('.lottery_time').text(localStorage.lottery_time)
                $('.JScore').text(localStorage.score)
                prizes.stop(res.err_msg.id)
            } else {
                prizes.stop('');
                self.model.open('alert', res.err_msg)
            }
        })
    },

    services: {
        //环境变更
        HOST: HOST + '/pufa',
        REMOTE: HOST + '/pufa/api.php',
        success: function (cb) {
            return function (res) {
                if (res.err_code == 10000) {
                    myAct.doGoHref('login.html');
                } else {
                    cb && cb(res)
                }
            }
        },
        code: function (data, cb) {
            //get code
            return $.ajax({
                url: this.REMOTE + '/PLogin/code',
                type: 'POST',
                data: data,
                success: cb
            })
        },
        /*
         * act_id 注册时是否报名 1/0
         */
        register: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PLogin/register',
                type: 'POST',
                data: data,
                success: cb
            })
        },
        login: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PLogin/login',
                type: 'POST',
                data: data,
                success: cb
            })
        },
        /*
         *
         *    重置密码接口
         *    api.php/PLogin/reset
         *    参数 phone account code

         */
        reset: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PLogin/reset',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*
         * 修改密码接口     api.php/PLogin/change  参数 old_password password confirm
         * */
        change: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PLogin/change',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        userCenter: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PLogin/userCenter',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },

        exchangeIndex: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PExchange/index',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        exchange: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PExchange/exchange',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        exchangeRecord: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PExchange/record',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*积分明细*/
        exchangeDetail: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PExchange/detail',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*抽奖操作*/
        lottery: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PLottery/doLottery',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*奖品列表*/
        lotteryIndex: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PLottery/index',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*抽奖记录*/
        lotteryRecord: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PExchange/lotteryRecord',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*获取最新活动 */
        activityIndex: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PActivity/index',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*分享加积分接口 */
        activityAddScore: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PActivity/addScore',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*报名 */
        exchangeEnroll: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PExchange/enroll',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*签到 */
        signIn: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PExchange/signIn',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*新手福利列表 */
        BeginnerWelfare: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PBeginnerWelfare/index',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*特殊福利列表 */
        special: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PExchange/indexForSpecial',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*修改个人中心 */
        updateUserCenter: function (data, cb) {

            return $.ajax({
                url: this.REMOTE + '/PLogin/updateUserCenter',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*任务列表 */
        tasks: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PEnterTask/index',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        /*任务报名 */
        taskEnter: function (data, cb) {
            return $.ajax({
                url: this.REMOTE + '/PEnterTask/enter',
                type: 'POST',
                data: data,
                success: this.success(cb)
            })
        },
        loadConfig:function(cb){
            return $.ajax({
                url: this.REMOTE + '/PLogin/loadConfig',
                type: 'GET',
                success: this.success(cb)
            })
        }
    }
})

_.templateSettings = {
    evaluate: /\{\{(.+?)\}\}/g,
    interpolate: /\{\{=(.+?)\}\}/g,
    escape: /\{\{-(.+?)\}\}/g
};

var myAct = new Activity()
